package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired

    private StringRedisTemplate redisTemplate;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     */
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入1条数据
        dishMapper.insert(dish);//后绪步骤实现

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

        //清理缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);


    }


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result<Object> deleteBatch(List<Long> ids) {
        //判断状态是启售不能删
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
                return Result.error(MessageConstant.DISH_ON_SALE);
            }
        }
        //2.查询当前菜品是否关联套餐，如果关联则不能删除
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealDishIds!=null && setmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.如果删除了菜品的话，则关联的口味数据也需要删除掉
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();

    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdwithFlavor(Long id) {
    Dish dish=dishMapper.getById(id);

    List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishId(id);


    DishVO dishVO=new DishVO();
    BeanUtils.copyProperties(dish,dishVO);
    dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改
     * @param dishDTO
     */
    @Override
    public Result updatewithFlavor(DishDTO dishDTO) {

    Dish dish=new Dish();
    BeanUtils.copyProperties(dishDTO,dish);

    dishMapper.update(dish);

    dishFlavorMapper.deleteDishFlavor(Arrays.asList(dish.getId()));
    List<DishFlavor> flavors = dishDTO.getFlavors();
    if (flavors!=null && flavors.size()>0){
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        dishFlavorMapper.insertBatch(flavors);
    }

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");

    return Result.success();
    }


    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public void starOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");

    }


    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {


        //构造redis中的key，规则：dish_分类id
        String key = "dish_" + dish.getCategoryId();

        //查询redis中是否存在菜品数据
        String dishVoListStr = redisTemplate.opsForValue().get(key);

        List<DishVO> dishVOSList = JSONArray.parseArray(dishVoListStr, DishVO.class);
        if(dishVOSList != null && dishVOSList.size() > 0){
            //如果存在，直接返回，无须查询数据库
            return dishVOSList;
        }

        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        redisTemplate.opsForValue().set(key,JSON.toJSONString(dishVOList));
        return dishVOList;
    }


    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}